/**
 * PHOSIDE: PHosphorylation Site IDentification Engine.
 * Copyright 2009 Digital Biology Lab, University of Missouri.
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 3 of the License, or (at your option) any later
 * version. <p/> This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more
 * details.
 */

package phoside.util;

import java.io.InputStream;
import java.io.IOException;

import java.net.URL;
import java.net.URLConnection;

/**
 *
 * @author gjj
 */
public class UrlUtil {
    private static final int msConnectionTimeout = 2000;
    //TODO: test when IOException is throwed
    public static InputStream getInputStream(String source) throws IOException {
        return getInputStream(source,4);
    }

    public static InputStream getInputStream(String source, int maxExp) throws IOException {
        InputStream stream = null;
        int expCount = 0;
        int timeOut = msConnectionTimeout;
        while (true) { // multiple chances
            try {
                URL url = new URL(source);
                URLConnection uc = url.openConnection();
                uc.setUseCaches(false); // don't use a cached page
                uc.setConnectTimeout(timeOut); // set timeout for connection
                stream = uc.getInputStream();
                break;
            } catch (IOException e) {
                if (expCount++==maxExp) {
                    throw(e);
                } else {
                    timeOut *= 2;
                }
            }
        }

        return stream;
    }

//    public static void main(String[] strs) {
//        try {
//            InputStream is = getInputStream("http://phosphat.mpimp-golm.mpg.de/phosphat.html?code=AT5G37970.1");
//            java.util.List<String> lines = IOUtil.readStringListAscii(
//                    new java.io.InputStreamReader(is));
//            for (String line:lines) {
//                System.out.println(line);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}
